package common_package

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"fmt"
)

// json
// 序列化json.Marshal()
// 反序列化 json.Unmarshal()

type Users struct {
	Username string `json:"user_name"`
	Password string `json:"password"`
}

func JsonSerializable() {
	user := Users{
		"heheyixiao",
		"123456",
	}
	data, err := json.Marshal(&user)
	if err != nil {
		fmt.Printf("序列号错误 err=%v\n", err)
	}
	fmt.Printf("user序列化后=%v\n", string(data))
	user2 := new(Users)
	json.Unmarshal(data, user2)
}

func JSONSerializable() {
	user := Users{
		"heheyixiao",
		"123456",
	}

	var result bytes.Buffer
	encoder := json.NewEncoder(&result)
	encoder.Encode(user)
	userBytes := result.Bytes()
	fmt.Println(string(userBytes))

	var account Users
	decoder := json.NewDecoder(bytes.NewReader(userBytes))
	decoder.Decode(&account)
	fmt.Println(account.Username, account.Password)
}

//标准库gob是golang提供的“私有”的编解码方式，它的效率会比json，xml等更高，特别适合在Go语言程序间传递数据。
func GobSerializable() {
	user := Users{
		"heheyixiao",
		"123456",
	}

	var result bytes.Buffer
	encoder := gob.NewEncoder(&result)
	encoder.Encode(user)
	userBytes := result.Bytes()
	//fmt.Println(userBytes)

	var account Users
	decoder := gob.NewDecoder(bytes.NewReader(userBytes))
	decoder.Decode(&account)
	fmt.Println(account.Username, account.Password)
}
